import 'package:english_words/english_words.dart';
import 'package:fish_redux/fish_redux.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import 'action.dart';
import 'state.dart';

Effect<HomePageState> buildEffect() {
  return combineEffects(<Object, Effect<HomePageState>>{
    Lifecycle.initState: _init,
    HomePageAction.onRandomMsg: _onRandomMsg,
    HomePageAction.onRefresh: _onRefresh,
    HomePageAction.onFetch: _onFetch,
  });
}

void _init(Action action, Context<HomePageState> ctx) async {
  ctx.dispatch(
    HomePageActionCreator.init(
      HomePageState(
        msg: 'Hello, World!',
        words: [],
        refreshController: RefreshController(initialRefresh: true),
      ),
    ),
  );
}

void _onRandomMsg(Action action, Context<HomePageState> ctx) {
  ctx.dispatch(HomePageActionCreator.randomMSg(
      HomePageState(msg: DateTime.now().toString())));
}

void _onRefresh(Action action, Context<HomePageState> ctx) async {
  await Future.delayed(Duration(milliseconds: 500)).then((e) {
    final List<WordPair> words = generateWordPairs().take(20).toList();
    ctx.state.refreshController.refreshCompleted();
    ctx.dispatch(HomePageActionCreator.refresh(words));
  });
}

void _onFetch(Action action, Context<HomePageState> ctx) async {
  await Future.delayed(Duration(milliseconds: 500)).then((e) {
    final List<WordPair> words = generateWordPairs().take(20).toList();
    ctx.state.refreshController.loadComplete();
    ctx.dispatch(HomePageActionCreator.fetch(words));
  });
}
